<?php
class Product_Service_Product
{
	protected $_modelProduct;
	protected $_modelOptions = null;
	protected $_modelOptionChoose = null;
	protected $_modelOptionValue = null;
	public $statusText = array(
				"2" => "Draft",
				"1" => "Activate",
				"0" => "Deleted"
			);
	public $logType = array(
				"0" => "Content Update",
				"1" => "Status Update",
				"2" => "Shelf/Warehouse Update",
			);
	public function __construct(){
		
	}
	
	public static function getInstance(){
		return new Product_Service_Product();
	}

	public static function getByProductId($id){		
		$obj = new Product_Model_Product();
		return $obj->getByProductId($id);		
	}
	public static function getByCondition($condition=array(),$type='*',$order=array('product_id'), $pageSize=0, $page=1)
	{ 
		$obj=new Product_Model_Product();

		$rows= $obj->getByCondition( $condition,$type,$order, $pageSize,$page);	
		return $rows;
	}
	/**
	* 获得产品目录
	* @param int $productId
	* @return array|false
	*/
	public static function getProductCategory($productId){
		$povServiceObj = new Product_Model_ProductOptionValue();
		$category = $povServiceObj->getByProductId($productId,1)->current();
		if($category instanceof Zend_Db_Table_Row){
			$category = $category->toArray();
			$pocService = new Product_Model_ProductOptionChoose();
			$poc = $pocService->getDbTable()->find($category['poc_id'])->current();
			if($poc instanceof Zend_Db_Table_Row){
				return $poc->toArray();
			}
		}
		return false;
	}
	
	/**
	* 获得产品信息
	* @param int $productId
	* @return array
	*/
	public static function getProductInfo($productId){
		$product = Product_Model_Product::getInstance()->getProduct($productId);
		if($product instanceof Zend_Db_Table_Row){
			$product = $product->toArray();
			
			//查找产品的关联选项
			$povServiceObj = new Product_Model_ProductOptionValue();
			$povs = $povServiceObj->getByProductId($productId)->toArray();
			$product['pov'] = $povs;
			//产品目录
			$product['category'] = self::getProductCategory($productId);
						
			return $product;
		}
		return false;
	}
	
	public function getAdapter(){
		$model = new Product_Model_Product();
		return $model->getAdapter();
	}
	
	public function update($row,$id){
		$model = new Product_Model_Product();
		return $model->update($row,$id);
	}
	
	public static function getAllCategory(){
		$optionModel = new Product_Model_ProductOptions();
		$option = $optionModel->getByName("Category");
		$choose = new Product_Model_ProductOptionChoose();
		$categorys = $choose->getAll($option['po_id']);
		if($categorys instanceof Zend_Db_Table_RowSet){
			return $categorys->toArray();
		}
		return false;
	}
	
	/**
	 * 根据产品ID与仓库 选择 包材
	 *
	 * @param unknown_type $productId
	 * @param unknown_type $warehouseId
	 * @return unknown
	 */
	public static function getByProductIdAndWarehouseId($productId,$warehouseId){
		$ppmModel = new Product_Model_PackageMap();
		$ppm = $ppmModel->getByProductIdAndWarehouseId($productId,$warehouseId);
		if($ppm instanceof Zend_Db_Table_Row){
			$ppm = $ppm->toArray();
			$pp = Product_Service_Package::getByPpid($ppm['package_id']);
			return $pp;
		}
		return false;
	}
	
	
	/**
	* 产品停用
	* @param array $productIds
	* @return 
	*/
	public function delete($productIds){
		$message = array();	
		foreach($productIds as $id){	
			$pp = new Product_Service_ProductProccess();		
			$result = $pp->submited(0,$id);		
			$message[$result['product_sku']] = $result['product_sku'].$result['msg'];			
		}
//		print_r($productIds);
//		print_r($message);
		return  $message;
	}
	/**
	* 产品激活
	* @param array $productIds
	* @return 
	*/
	public function activate($productIds){
		$message = array();
		//判断plan剩余的sku数量
		$planService = new Plan_Service_Plan();
	
		foreach($productIds as $id){
			$pp = new Product_Service_ProductProccess($id);
			$product = $this->getProductInfo($id);
	 		$planUsage = $planService->getCurrentPlanUsage($product['customer_id']);
	 		
			$max = $planUsage['sku_qty'] - $planUsage['sku_used'];
			
			if($max<=0){
				$message[$product['product_sku']] = $product['customer_id']."当前套餐最多只能激活".intval($planUsage['sku_qty'])."已经激活".intval($planUsage['sku_used']);
			}else{
				$result = $pp->submited(1,$id);	
				$message[$result['product_sku']] = $result['product_sku'].$result['msg'];
			}
		}
//		print_r($message);
//		print_r($product);die();
		return $message;
	}
	
	/**
	* 产品转为草稿
	* @param array $productIds
	* @return 
	*/
	public function inactivate($productIds){
		$message = array();		
		foreach($productIds as $id){
			// $product = $this->getProductInfo($id);
			// $result = $this->changeProductStatus($id,2);
			$pp = new Product_Service_ProductProccess($id);
			$result = $pp->submited(2,$id);
			$message[$result['product_sku']] = $result['msg'];
		}
		return $message;
	}
	/**
	 * 获得打印信息
	 * @param array $row
	 * @return
	 */
	public function getPrintInfo($rows,$customerId = null){
		$result = array();
		//		$customer = new Product_Service_Customer();
		foreach($rows as $key => $row){
			$product = $this->getByProductId($key);
			$product['category']="";
			$category = $this->getProductCategory($key);
			$category&&$product['category']=$category['poc_value'];
			//			$result[$key]["customer"] = $customer->get($customerId);
			if($row > 0){
				for($i=0;$i<$row;$i++){
					$result[] = $product;
				}
			}
				
		}
		return $result;
	}
	/**
	 * 获得 产品标签 打印信息
	 * @param array $row
	 * @return
	 */
	public function getPrintLabelInfo($rows,$customerId = null){
		$session = new Zend_Session_Namespace('userAuth');
		$userId = isset($session->userID)?$session->userID:0;
		$userInfo = User_Service_User::getByUserId($userId);		//操作人信息
	
		$result = array();
		//		$customer = new Product_Service_Customer();
		foreach($rows as $key => $row){
			$product = $this->getByProductId($key);
			$product['category']="";
			$category = $this->getProductCategory($key);
			$category&&$product['category']=$category['poc_value'];
			//			$result[$key]["customer"] = $customer->get($customerId);
			if($row > 0){
				$product['operator_flag'] = 1;
				$product['operator'] = $userInfo['name'];
				$result[] = $product;
				for($i=0;$i<$row;$i++){
					$product['operator_flag'] = 0;
					$result[] = $product;
				}
			}
				
		}
		return $result;
	}
	

	
	/*根据状态码获得包装
	*return String
	*/
	public static function getPackageType($type)
	{ $lang = Zend_Registry::get('lang');
		$package_type=array(
			0=>$lang['need_packaging'],
			1=>$lang['has_packaging'],
		);
		return $package_type[$type];
	}
	
	/*根据状态码获得状态描述
	*return String
	*/
	public static function getProductStatus($status)
	{ 
	    $lang = Zend_Registry::get('lang');
		$products_status=array(
			0=>$lang['delete'],
			1=>$lang['activated'],
			2=>$lang['draft'],
		);
		return $products_status[$status];
	}
	
	/*根据状态码获得状态描述
	*return String
	*/
	public static function getWarehouseStatus($status)
	{ 
	    $lang = Zend_Registry::get('lang');
		$warehouses_status=array(
			0=>$lang['new_product'],
			1=>$lang['has_received_product'],
		);
		return $warehouses_status[$status];
	}
	
	/**
	* 产品选项
	* @param $productId,$showAll是否显示全部选项
	* @return 
	*/
	public function getProductOptions($productId = null,$showAll = false){		
		$productOption = new Product_Model_ProductOptions();
		if(empty($productId)){
			$options = $productOption->getAll();	
			$options = $options->toArray();	
				
			foreach($options as $key=>$val){				
				if($val['po_choose_type']==0){
					$productOptionChoose = new 	Product_Model_ProductOptionChoose();
					$options[$key]['product_option_choose'] = $productOptionChoose->getAll($val['po_id'])->toArray();
	
				}
			}	
		}else{
			$productOptionValue = new Product_Model_ProductOptionValue();
			$productOptionValues = $productOptionValue->getByProductId($productId);
			
			$productOptionValues = $productOptionValues->toArray();
			$options = array();
			
			$pov_arr = array();
			foreach($productOptionValues as $key=>$v){
				$options[$key] = $productOption->getById($v['po_id'])->toArray();
			}	
			
//			print_r($productOptionValues);
			foreach($options as $key=>$val){				
				if($val['po_choose_type']==0){
					$productOptionChoose = new 	Product_Model_ProductOptionChoose();
					$options[$key]['poc_id'] = $productOptionValues[$key]['poc_id'];	
					$options[$key]['product_option_choose'] = $productOptionChoose->getAll($val['po_id'])->toArray();
				}else{
					$options[$key]['po_value'] = $productOptionValues[$key]['po_value'];						
				}
			}	
		}
//		print_r($options);
		return $options;
	}
	
	
	
	
	/**
	* 更新产品
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function edit($row,$productId=null,$productOptionValues = array()){
		$error = $this->validate($row,$productOptionValues,true,$productId);
		if(!empty($error)){
			return $error;
		}
		$modelOptionValue = new Product_Model_ProductOptionValue();		
		$dbAdapter = $modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		$modelProduct = new Product_Model_Product();
		$modelOptions = new Product_Model_ProductOptions();
		try{
			$flag = $this->update($row,$productId);
			if($flag > 0){
				$modelOptionValue->deleteByProductId($productId);//删除
				foreach($productOptionValues as $key => $value){					
					$insertRow = array(
						"po_id" => $value['po_id'],
						"po_value" => $value['po_value'],
						"poc_id" => $value['poc_id'],
						"product_id" => $productId,
					);					
					$modelOptionValue->getDbTable()->insert($insertRow);
				}
				
				$this->writeLog($row,$productId,"0","0","0");
				$dbAdapter->commit();
				return true;
			}else{
				$dbAdapter->rollback();
				return array('Internal error! Please try again.');//添加失败				
			}
		}catch(Exception $e){
			echo $e->getMessage();
			$dbAdapter->rollback();
			return false;
		}
	}
	/**
	* 创建产品
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function create($row,$productOptionValues = array()){
		$error = $this->validate($row,$productOptionValues);
		if(!empty($error)){
			return $error;
		}
		$modelOptionValue = new Product_Model_ProductOptionValue();		
		$dbAdapter = $modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		$modelProduct = new Product_Model_Product();
		$modelOptions = new Product_Model_ProductOptions();
		try{
			$insertId = $modelProduct->add($row);
			if($insertId > 0){
				
				foreach($productOptionValues as $key => $value){					
					$insertRow = array(
						"po_id" => $value['po_id'],
						 "po_value" => $value['po_value'],
						'poc_id' => $value['poc_id'],
						"product_id" => $insertId,
					);					
					$modelOptionValue->getDbTable()->insert($insertRow);
				}
				
				$this->writeLog($row,$insertId,"0","0","0");
				$dbAdapter->commit();
				return true;
			}else{
				$dbAdapter->rollback();
				return array('Internal error! Please try again.');//添加失败				
			}
		}catch(Exception $e){
			echo $e->getMessage();
			$dbAdapter->rollback();
			return false;
		}
	}
	
	/**
	* 验证产品数据
	* @param array $row
	* @param int $customerId
	* @param array $productOptionValues
	* @param boolean $edit
	* @param int $productId 如果$edit 为true 需要设置$productId
	* @return true|array  success return true or failure return array
	*/
	public function validate($row,$productOptionValues = array(),$edit = false,$productId=null){
//		print_r($row);
		$error = array();
		if("" == $row['customer_id']){
			$error[] = "CustomerId required";//客户ID必须
		}else{
			$customer_model_customer = new Customer_Model_Customer();
			$customer = $customer_model_customer->getByCustomerId($row['customer_id']);
			if(!$customer){
				$error[] = "CustomerId not exists";//客户ID不存在			
			}
		}
		if("" == $row['product_title']){
			// $error[] = I18n::getInstance()->translate("0000011");//产品名称不能为空
			$error[] = "SKUName required";
		}
		if("" == $row['product_weight']){
			// $error[] = I18n::getInstance()->translate("0000012");//产品重量不能为空
			$error[] = "Weight required";
		}else if(!is_numeric($row['product_weight'])){
			$error[] = "Weight must be numeric";
		}
		
		if("" == $row['product_length']){
			$error[] = "Length required";
		}else if(!is_numeric($row['product_length'])){
			$error[] = "Lenght must be numeric";
		}
		if("" == $row['product_width']){
			$error[] = "Width required";
		}else if(!is_numeric($row['product_width'])){
			$error[] = "Widht must be numeric";
		}
		if("" == $row['product_height']){
			$error[] = "Height required";
		}else if(!is_numeric($row['product_height'])){
			$error[] = "Height must be numeric";
		}
		
		if("" == $row['product_sku']){
			// $error[] = I18n::getInstance()->translate("0000013");//产品sku不能为空
			$error[] = "SKU required";
		}else if($this->existsSku($row['customer_id'],$row['product_sku'],$edit,$productId)){
			$error[] = "SKU exists";//sku已经存在
		}
		
		$modelOptions = new Product_Model_ProductOptions();
		
		foreach($productOptionValues as $key => $value){
			$option =$modelOptions->getDbTable()->find($key)->current();
			if(isset($option->po_type)){
				if($option->po_type == 1 && $value == ""){
					// $error[] = I18n::getInstance()->translate("0000014");//
					$error[] = $option->po_name." Required";
				}
			}else{
//				$error[] = "Category not found";
			}
		
		}
		return $error;
	}
	
	/**
	* 检查sku是否存在
	* @param string $sku
	* @param int $customerId
	* @param boolean $edit
	* @return boolean
	*/
	public function existsSku($customerId,$sku,$edit = false,$productId = null){
		$modelProduct = new Product_Model_Product();
		$row = $modelProduct->getByCustomerIdAndSku($customerId,$sku);
		if(empty($row)){
			return false;
		}
		
		if($edit){//编辑时要判断相等的sku是否和当前productId相等
			 if($row->product_id != $productId) return true;
			 return false;
		}
		
		
		return true;
	}
	/**
	* 产品修改日志记录
	* $param array $row
	* $param int $productId
	* $param int $type
	* $param int $preStatus
	* $param int $curStatus
	* @return void
	*/
	public function writeLog($row,$productId,$type,$preStatus="",$curStatus=""){
		$noteArray = array(
			"product_sku" => "SKU",
			"product_title" => "SKUName",
			"product_length" => "lenght",
			"product_width" => "width",
			"product_height" => "height",
			"product_weight" => "weight",
			"product_declared_value" => "declare value",
		);
		$note = "";
		foreach($row as $key => $value){
			if(isset($noteArray[$key])){
				$note .= $noteArray[$key].":".$value.";";
			}
		}
		$dbTable = Product_Model_ProductHistory::getInstance()->getDbTable();
		$log = array(
			"ph_type" => $type,
			"product_id" => $productId,
			"ph_statu_pre" => $preStatus,
			"ph_statu_now" => $curStatus,
			"ph_note" => $note,
			"ph_add_time" => date("Y-m-d H:i:s"),
			"ph_ip" => $_SERVER['REMOTE_ADDR']
		);
		$dbTable->insert($log);
	}
	
	/**
	* 获得日志信息
	* @param int $productId
	* @param int $customerId
	* @param int $page
	* @param int $pageSize
	* @return array
	*/
	public function getLog($productId,$page,$pageSize,$customerId=null){
		$serviceObj = Product_Model_ProductHistory::getInstance();
		$product = $this->getProductInfo($productId,$customerId);
		$logs = $serviceObj->getByProductId($product['product_id'],$page,$pageSize)->toArray();
		foreach($logs as $key => $value){
			$logs[$key]['type'] = $this->logType[$value["ph_type"]];
			$logs[$key]['statu_pre'] = $this->statusText[$value["ph_statu_pre"]];
			$logs[$key]['statu_now'] = $this->statusText[$value["ph_statu_now"]];
		}
		return $logs;
	}
	
	/**
	* 获得日志总数
	* @param int $productId
	* @param int $customerId
	* @return int
	*/
	public function getLogCount($productId){
		$serviceObj = Product_Model_ProductHistory::getInstance();
		return $serviceObj->getCount($productId);
	}
	
	public function getPackageByProductId($productId=null){
		$wareHouses = Warehouse_Service_Warehouse::getAll();
		$customerId = array("0");
		if(!empty($productId)){
			$product = 	self::getByProductId($productId);
			if($product){
				$customerId[] = $product['customer_id'];				
			}
		}
//		print_r($customerId);exit;
		foreach($wareHouses as $k=>$v){
			$packages = Product_Service_Package::getAll($v['warehouse_id'],$customerId);			
			$wareHouses[$k]['packages'] = $packages;
		}
//		print_r($wareHouses);
		return $wareHouses;
	}
	
	/**
	 * 根据产品ID与仓库 选择 包材
	 *
	 * @param unknown_type $productId
	 * @param unknown_type $warehouseId
	 * @return unknown
	 */
	public function getPackageMapByProductId($productId){
		$modelPackageMap = new Product_Model_PackageMap();
		$packageMaps = $modelPackageMap->getByProductId($productId);
		if($packageMaps instanceof Zend_Db_Table_Row){
			return $packageMaps->toArray();
		}		
		return $packageMaps;
	}
	
	
	public function getPackageNameByProductId($productId){
		$modelPackageMap = new Product_Model_PackageMap();
		$packageMaps = $modelPackageMap->getByProductId($productId);
		if($packageMaps instanceof Zend_Db_Table_Row){
			 $arr = $packageMaps->toArray();
			 $result =  Product_Service_Package::getByPpid($arr['package_id']);
			 if(!empty($result)){
			 	return $result['pp_name'];
			 }
		}		
		return "";
	}
	
	/**
	* 读取上传文件
	* @param string $fileName
	* @return array
	*/
	public function readUploadFile($fileName,$filePath){
		$columnMap = array(
			"ProductNo" => "product_sku",
			"ProductName" => "product_title",
			"Category" => "Category",
			"UOM" => "UOM",
			"Length" => "product_length" ,
			"Height" => "product_height",
			"Width" => "product_width",
			"Weight" => "product_weight" ,
			"Declare Value" => "product_declared_value",
			"Min Qty" => "Min_Qty",
			"CustomerId" => "customer_id",
		);
		$pathinfo = pathinfo($fileName);
		$fileData = array();
		if($pathinfo["extension"] == "xls"){
			$fileData = Product_Service_Upload::readEXCEL($filePath);
		}elseif($pathinfo["extension"] == "csv"){
			$fileData = Product_Service_Upload::readCSV($filePath);			
		}else{
			return false;
		}
		foreach($fileData[0] as $key => $value){
			if(isset($columnMap[$value])){
				$fileData[0][$key] = $columnMap[$value];
			}
		}
		$result = array();
		foreach($fileData as $key => $value){
			//将第一行value转成其他行的key
			if ($key == 0){
				continue;
			}
			foreach($value as $vKey => $vValue){
				if($fileData[0][$vKey] == "") continue;
				$result[$key][$fileData[0][$vKey]] = $vValue;
			}
		}
//		print_r($result);die();
		return $result;
	}
	
	/**
	* 获得创建产品图片上传的临时目录
	* return string
	*/
	public function getPictureUploadDir(){		
		$customerDir = APPLICATION_PATH."/../data/";
		if(!file_exists($customerDir)){
			if(mkdir($customerDir)){
				chmod($customerDir,0777);
			}
		}
		return $customerDir;
	}
	
	
	/**
	 * 异常库存
	 * return string
	 */
	public function getUnnormalProduct(){
		$list = array();
		
		
	}
	
	/**
	 * 通过SKU与客户ID或其他条件，返回一行数据
	 */
	public static function getRowByCond($cond,$type='*'){		
		$obj = new Product_Model_Product();
		return $obj->getRowByCond($cond,$type);		
	}
	
	/**
	* 获得产品创建的下拉框选项
	* @return array 
	*/
	public function getSelectOptions(){
		if($this->_modelOptions == null){
			$this->_modelOptions = new Product_Model_ProductOptions();
		}
		if($this->_modelOptionChoose == null){
			$this->_modelOptionChoose = new Product_Model_ProductOptionChoose();
		}
		$options = $this->_modelOptions->getAll();
		$selects = array();
		foreach($options as $option){
			$optionChooses = $this->_modelOptionChoose->getAllByOption($option->po_id);
			$select = array(
				"id" => $option->po_id,
				"name" => $option->po_name, 
				"po_choose_type" => $option->po_choose_type, 
				"desc" => $option->po_description,
				"required" => $option->po_type,
				"options" => $optionChooses->toArray(), 
			);
			$selects[] = $select;
		}
		return $selects;
	}
	
	/**
	* 通过产品id获得产品图片
	* @param int $productId
	* @return array
	*/
	public function getProductPicture($productId){
		return Product_Model_ProductAttached::getInstance()->getByProductId($productId)->toArray();
	}
	
	/**
	* 通过产品id获得产品外链图片
	* @param int $productId
	* @return array
	*/
	public function getProductLinks($productId){
		return Product_Model_ProductAttached::getInstance()->getLinksByProductId($productId)->toArray();
	}
	
	/**
	* 更新产品
	* @param int $productId
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function updateInfo($productId,$row,$productOptionValues=array(),$pictures=array(),$links=array(),$customerId = null){
		$error = $this->validate($row,$customerId,$productOptionValues,true,$productId);
		if(!empty($error)){
			return $error;
		}
		$productInfoPre = $this->getProductInfo($productId);
		if($this->_modelOptionValue == null){
			$this->_modelOptionValue = new Product_Model_ProductOptionValue();
		}
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			if($productInfoPre['product_warehouse_status'] >0){//第一次收货
				$dbAdapter->rollback();
				return array("Failure,the product status must  never receiving");
			}
			//判断产品库存
			$ProductStocket = Product_Service_ProductStocket::getByProductId($productInfoPre['product_id']);
			if($ProductStocket['ps_quantity'] > 0||$ProductStocket['ps_quantity_hold'] > 0){
				$dbAdapter->rollback();
				return array("Failure,the product quantity in warehouse must be 0");
			}
			$row["customer_id"] = $productInfoPre["customer_id"];
			$dbTable = $this->_modelProduct->getDbTable();
			$where = $dbTable->getAdapter()->quoteInto("product_id = ?",$productId);
			$updateNums = $dbTable->update($row,$where);
			
			foreach($productOptionValues as $key => $value){
				//查询option
				if($this->_modelOptions == null){
					$this->_modelOptions = new Product_Model_ProductOptions();
				}
				$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
				if($option['po_choose_type'] == 0){
					$updateRow['poc_id'] = $value['poc_id'];
				}else{
					$updateRow['po_value'] = $value['poc_id'];
				}
				
				$oWhere = $dbAdapter->quoteInto("product_id = ?",$productId);
				$oWhere .= $dbAdapter->quoteInto(" and po_id = ?",$value['po_id']);
				$this->_modelOptionValue->getDbTable()->update($updateRow,$oWhere);
			}
			//更新图片
			$this->addPicture($customerId,$productId,$row['product_sku'],$pictures);
			//添加外链图片
			$this->addLinks($links,$productId,true);
			$productInfoCur = $this->getProductInfo($productId);
			$this->writeLog($row,$productId,"0",$productInfoPre['product_status'],$productInfoCur['product_status']);
			$dbAdapter->commit();
			return true;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return false;
		}
	}
	
	/**
	* 更新产品
	* @param int $productId
	* @param array $row
	* @param array $productOptionValues
	* @param array $pictures
	* @param int $customerId
	* @return boolean|array 
	*/
	public function updateQty($productId,$productOptionValues=array(),$pictures=array(),$links=array(),$customerId = null){
		
		$productInfoPre = $this->getProductInfo($productId);
		if($this->_modelOptionValue == null){
			$this->_modelOptionValue = new Product_Model_ProductOptionValue();
		}
		$dbAdapter = $this->_modelOptionValue->getDbTable()->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			
			$row["customer_id"] = $productInfoPre["customer_id"];
			$dbTable = $this->_modelProduct->getDbTable();
			$where = $dbTable->getAdapter()->quoteInto("product_id = ?",$productId);
			$updateNums = $dbTable->update($row,$where);
			
			foreach($productOptionValues as $key => $value){
				//查询option
				if($this->_modelOptions == null){
					$this->_modelOptions = new Product_Model_ProductOptions();
				}
				$option = $this->_modelOptions->getDbTable()->find($value['po_id'])->current();
				if($option['po_choose_type'] == 0){
					$updateRow['poc_id'] = $value['poc_id'];
				}else{
					$updateRow['po_value'] = $value['poc_id'];
				}
				
				$oWhere = $dbAdapter->quoteInto("product_id = ?",$productId);
				$oWhere .= $dbAdapter->quoteInto(" and po_id = ?",$value['po_id']);
				$this->_modelOptionValue->getDbTable()->update($updateRow,$oWhere);
			}
			//更新图片
			$this->addPicture($customerId,$productId,$productInfoPre['product_sku'],$pictures);
			//添加外链图片
			$this->addLinks($links,$productId,true);
			$this->writeLog(array(),$productId,"0",'','','min qty update or picture update');//内容修改
			$dbAdapter->commit();
			return true;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return false;
		}
	}
	
	/**
	* 上传图片后移动目录并将路径保存到数据库
	* @param int $customerId
	* @param int $productId
	* @param mix $sku
	* @rparam array $pictures
	* @return void
	*/
	public function addPicture($customerId,$productId,$sku,$pictures){
		//将图片放到data/customerId/sku下面
		$customerDir = $this->getPictureUploadDir2($customerId);
		$productIdDir = $customerDir."/".$productId;
		if(!file_exists($productIdDir)){
			if(mkdir($productIdDir)){
				chmod($productIdDir,0777);
			}
		}
		//删除已经存在的图片地址
		Product_Model_ProductAttached::getInstance()->deleteByProductId($productId);
		if(file_exists($productIdDir)){
			foreach ($pictures as $picture){
				$oldFile = $customerDir."/".$picture;
				if(file_exists($oldFile)){
					$newFile = $productIdDir."/".$picture;
					file_put_contents($newFile,file_get_contents($oldFile));					
					unlink($oldFile);
				}
				//将图片名称保存到数据库
				$attRow = array(
					"product_id" => $productId,
					"pa_path" => $picture,
					"pa_file_type" => "img",
					"pa_status" => 1,
					"languages_id" => $this->getLoginInfo()->lang?$this->getLoginInfo()->lang:1,
					"pa_last_update" => date("Y-m-d H:i:s"),
				);
				Product_Model_ProductAttached::getInstance()->getDbTable()->insert($attRow);
			}
		}
	}
	
	/**
	* 获得创建产品图片上传的临时目录
	* return string
	*/
	public function getPictureUploadDir2($customerId){
		$customerDir = "../data/images/".$customerId;
		if(!file_exists($customerDir)){
			if(mkdir($customerDir)){
				chmod($customerDir,0777);
			}
		}
		return $customerDir;
	}
	
	/**
	* 添加外部链接图片
	* @param int $productId
	* @param array $links
	* @param boolean $edit
	* @return void
	*/
	public function addLinks($links,$productId,$edit = false){
		if($edit){//修改时先删除之前的
			Product_Model_ProductAttached::getInstance()->deleteLinksByProductId($productId);
		}
		$customerInfo = $this->getCustomerByPid($productId);
		
		foreach($links as $link){
			$linksRow = array(
				"product_id" => $productId,
				"pa_path" => $link,
				"pa_file_type" => "link",
				"pa_status" => 1,
				"languages_id" => $customerInfo['languages_id']?$customerInfo['languages_id']:1,
				"pa_last_update" => date("Y-m-d H:i:s"),
			);
			Product_Model_ProductAttached::getInstance()->getDbTable()->insert($linksRow);
		}
	}
	
	/**
	* 获得 customer 信息
	* return Zend_Session_NameSpace
	*/
	public function getCustomerByPid($productId){
		$productInfo = $this->getProductInfo($productId);
		$customerInfo = Customer_Service_Customer::getByCustomerId($productInfo['customer_id']);
		return $customerInfo;
	}
	
	/**
	* 通过产品id获得产品图片,包括上传图片和网络图片
	* @param int $productId
	* @return array
	*/
	public function getAllProductPicture($productId){
		return Product_Model_ProductAttached::getInstance()->getAllByProductId($productId)->toArray();
	}
	
	/**
	* 根据产品状态码获得状态描述
	* @param int $status
	* @return string
	*/
	public function getStatusText($status){
		
		return @$this->statusText[$status];
	}
	
}